package com.agileai.miscdp.hotweb.ui.views;

import java.io.File;
import java.io.IOException;
import java.net.URL;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;

import com.agileai.miscdp.DeveloperConst;
import com.agileai.miscdp.MiscdpPlugin;
import com.agileai.miscdp.hotweb.ConsoleHandler;
import com.agileai.miscdp.hotweb.domain.BaseFuncModel;
import com.agileai.miscdp.hotweb.domain.CustomFuncModel;
import com.agileai.miscdp.hotweb.domain.FuncModule;
import com.agileai.miscdp.hotweb.domain.FuncProject;
import com.agileai.miscdp.hotweb.domain.ProjectConfig;
import com.agileai.miscdp.hotweb.domain.mastersub.MasterSubFuncModel;
import com.agileai.miscdp.hotweb.domain.pickfill.PickFillFuncModel;
import com.agileai.miscdp.hotweb.domain.portlet.PortletFuncModel;
import com.agileai.miscdp.hotweb.domain.query.QueryFuncModel;
import com.agileai.miscdp.hotweb.domain.simplest.SimplestFuncModel;
import com.agileai.miscdp.hotweb.domain.standard.StandardFuncModel;
import com.agileai.miscdp.hotweb.domain.treecontent.TreeContentFuncModel;
import com.agileai.miscdp.hotweb.domain.treefill.TreeFillFuncModel;
import com.agileai.miscdp.hotweb.domain.treemanage.TreeManageFuncModel;
import com.agileai.miscdp.hotweb.ui.dialogs.CreateDirDialog;
import com.agileai.miscdp.hotweb.ui.editors.mastersub.MasterSubModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.module.FuncModuleEditor;
import com.agileai.miscdp.hotweb.ui.editors.pickfill.PickFillModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.portlet.PortletModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.query.QueryModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.simplest.SimplestModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.standard.StandardModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.treecontent.TreeContentModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.treefill.TreeFillModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.treemanage.TreeManageModelEditor;
import com.agileai.miscdp.hotweb.ui.wizards.FuncModelWizard;
import com.agileai.miscdp.hotweb.ui.wizards.HotwebProjectWizard;
import com.agileai.miscdp.server.HotServerManage;
import com.agileai.miscdp.util.ImageUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.FileUtil;
import com.agileai.util.StringUtil;
/**
 * 功能模型树
 */
public class FuncModelTreeView extends ViewPart {
	private TreeViewer funcTreeViewer;
	private DrillDownAdapter drillDownAdapter;
	private Action createDirAction;
	private Action deleteAppAction;
	private Action refreshAppAction;
	private Action browseLocalAppAction;
	private Action openBrowserAppAction;
	private Action restartContextAction;
	private Action loadContextAction;
	private Action unloadContextAction;
	private Action editContextAction;
	
	private Action createFuncAction;
	private Action deleteNodeAction;
	private Action doubleClickAction;
	
	private Action openDirAction;
	private Action closeDirAction;
	private Action refreshAction;
	private Action createAppAction;
	
	private TreeViewContentProvider treeViewContentProvider;
	public FuncModelTreeView() {
	}

	public TreeViewer getFuncTreeViewer() {
		return funcTreeViewer;
	}
	
	public void createPartControl(Composite parent) {
		funcTreeViewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		
		drillDownAdapter = new DrillDownAdapter(funcTreeViewer);
		treeViewContentProvider = new TreeViewContentProvider(this);
		funcTreeViewer.setContentProvider(treeViewContentProvider);
		TreeViewLabelProvider treeViewLabelProvider = new TreeViewLabelProvider();
		funcTreeViewer.setLabelProvider(treeViewLabelProvider);
		funcTreeViewer.setInput(getViewSite());

		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				if (obj instanceof TreeObject) {
					TreeObject curNode = (TreeObject) obj;
					String nodeType = curNode.getNodeType();
					if (TreeObject.NODE_PROJECT.equals(nodeType)){
						fillFuncProjectContextMenu(manager);
					}
					else if (TreeObject.NODE_COMPOSITE.equals(nodeType)){
						fillFuncModuleContextMenu(manager);
					}
					else{
						fillFuncModelContextMenu(manager);						
					}
				}
			}
		});
		Menu menu = menuMgr.createContextMenu(funcTreeViewer.getControl());
		funcTreeViewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, funcTreeViewer);
	}
	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalToolBar(bars.getToolBarManager());
	}
	private void fillFuncProjectContextMenu(IMenuManager manager) {
		manager.add(createDirAction);
		manager.add(deleteAppAction);
		manager.add(new Separator());
		manager.add(restartContextAction);
		manager.add(refreshAppAction);
		manager.add(openBrowserAppAction);
		manager.add(browseLocalAppAction);
		manager.add(loadContextAction);
		manager.add(unloadContextAction);
		manager.add(editContextAction);
		
//		drillDownAdapter.addNavigationActions(manager);
//		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	private void fillFuncModuleContextMenu(IMenuManager manager) {
		manager.add(createDirAction);
		manager.add(createFuncAction);
		manager.add(deleteNodeAction);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	private void fillFuncModelContextMenu(IMenuManager manager) {
		manager.add(deleteNodeAction);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}

	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(createAppAction);
		manager.add(refreshAction);
		manager.add(openDirAction);
		manager.add(closeDirAction);
		manager.add(new Separator());
		drillDownAdapter.addNavigationActions(manager);
	}
	private void makeDeleteAppAction(){
		deleteAppAction = new Action() {
			public void run() {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				TreeObject treeObject = null;
				if (obj instanceof TreeObject) {
					treeObject = (TreeObject) obj;
					String projectName = treeObject.getProjectName();
					if (MessageDialog.openConfirm(funcTreeViewer.getControl().getShell(),"提示信息","您确认要删除\""+projectName+"\"应用吗?")){
						IWorkspace workspace = ResourcesPlugin.getWorkspace();
						final IProject project = workspace.getRoot().getProject(projectName);
						IWorkspaceRunnable operation = new IWorkspaceRunnable() {
							public void run(IProgressMonitor monitor) throws CoreException {
								project.delete(true, monitor);
								refreshView();
							}
						};
						try {
							workspace.run(operation,new NullProgressMonitor());						
						} catch (Exception e) {
							MiscdpPlugin.getDefault().logError(e.getLocalizedMessage(),e);
						}						
					}
				}
			}
		};
		deleteAppAction.setText("删除应用");
		deleteAppAction.setToolTipText("删除应用");
		deleteAppAction.setImageDescriptor(ImageUtil.getDescriptor("delete"));
	}
	
	private void makeRefreshAppAction(){
		refreshAppAction = new Action() {
			public void run() {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				TreeObject treeObject = null;
				if (obj instanceof TreeObject) {
					treeObject = (TreeObject) obj;
					final String appName = treeObject.getProjectName();
					
					Job job = new Job("RefreshJavaProject") {
						@Override
						protected IStatus run(IProgressMonitor monitor) {
				            monitor.beginTask(this.getName(), 6000);   
							IProject iProject = MiscdpUtil.getProject(appName);
							try {
								iProject.refreshLocal(IProject.DEPTH_INFINITE, monitor);						
							} catch (Exception e) {
								MiscdpPlugin.getDefault().logError(e.getLocalizedMessage(), e);
							}
				            monitor.done();   
				            return Status.OK_STATUS;   
						}
					};
					job.schedule();  
				}
			}
		};
		refreshAppAction.setText("刷新应用");
		refreshAppAction.setToolTipText("刷新应用");
		refreshAppAction.setImageDescriptor(ImageUtil.getDescriptor("refresh"));
	}
	
	private void makeCreateDirAction(){
		createDirAction = new Action() {
			public void run() {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				CreateDirDialog dialog = new CreateDirDialog(FuncModelTreeView.this,funcTreeViewer.getTree().getShell());
				TreeObject treeObject = null;
				if (obj instanceof TreeObject) {
					treeObject = (TreeObject) obj;
					dialog.setFuncPId(treeObject.getId());
					dialog.setFuncPName(treeObject.getName());
				}
				
				int returnCode = dialog.open();
				if (returnCode == 0){
					String projectName = treeObject.getProjectName();
					TreeObject newNode = new TreeObject(dialog.getFuncId(),dialog.getFuncName());
					newNode.setNodeType(TreeObject.NODE_COMPOSITE);
					newNode.setProjectName(projectName);
					treeObject.addChild(newNode);
					
					TreeViewContentProvider treeViewContentProvider = (TreeViewContentProvider)funcTreeViewer.getContentProvider();
					TreeObject projectTreeObject = treeViewContentProvider.getProjectTreeObject(projectName);
					MiscdpUtil.updateTreeIndexFile(projectTreeObject);
					
					Object[] elements = funcTreeViewer.getExpandedElements(); 
					TreePath[] treePaths = funcTreeViewer.getExpandedTreePaths(); 
					funcTreeViewer.refresh();
					funcTreeViewer.setExpandedElements(elements); 
					funcTreeViewer.setExpandedTreePaths(treePaths); 
				}
			}
		};
		createDirAction.setText("创建目录");
		createDirAction.setToolTipText("创建目录");
		createDirAction.setImageDescriptor(ImageUtil.getDescriptor("add_folder"));
	}
	
	private void makeBrowseLocalAppAction(){
		browseLocalAppAction = new Action() {
			public void run() {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				TreeObject treeObject = null;
				if (obj instanceof TreeObject) {
					treeObject = (TreeObject) obj;
					String appName = treeObject.getProjectName();
					IProject project = MiscdpUtil.getProject(appName);
					String path = project.getLocation().toFile().getAbsolutePath();
					try {
						Runtime.getRuntime().exec("explorer " + path);
					} catch (IOException e) {
						ConsoleHandler.error(e.getLocalizedMessage());
					}
				}
			}
		};
		browseLocalAppAction.setText("本地查看");
		browseLocalAppAction.setToolTipText("本地查看");
		browseLocalAppAction.setImageDescriptor(ImageUtil.getDescriptor("browse"));
	}
	
	private void makeOpenBrowserAppAction(){
		openBrowserAppAction = new Action() {
			public void run() {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				TreeObject treeObject = null;
				if (obj instanceof TreeObject) {
					treeObject = (TreeObject) obj;
					String appName = treeObject.getProjectName();
				    IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
				    try {
					    IWebBrowser browser = support.createBrowser("OpenWebsite");
					    ProjectConfig projectConfig = MiscdpUtil.getProjectConfig(appName);
					    String serverPort = projectConfig.getServerPort();
					    browser.openURL(new URL(("http://localhost:"+serverPort+"/"+appName)));
					} catch (Exception e) {
						MiscdpPlugin.getDefault().logError(e.getLocalizedMessage(), e);
					}
				}
			}
		};
		openBrowserAppAction.setText("浏览运行");
		openBrowserAppAction.setToolTipText("浏览运行");
		openBrowserAppAction.setImageDescriptor(ImageUtil.getDescriptor("openbrowser"));
	}
	
	private void makeLoadContextAction(){
		loadContextAction = new Action() {
			public void run() {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				TreeObject treeObject = null;
				if (obj instanceof TreeObject) {
					treeObject = (TreeObject) obj;
					String appName = treeObject.getProjectName();
					ConsoleHandler.info("loading application <" + appName + ">....");
					ProjectConfig projectConfig = MiscdpUtil.getProjectConfig(appName);
					String serverAddress = projectConfig.getServerAddress();
					String serverPort = projectConfig.getServerPort();
					try {
						IProject project = MiscdpUtil.getProject(appName);
						String docBase = project.getLocation().toString()+"/WebRoot";
						HotServerManage hotServerManage = MiscdpUtil.getHotServerManage(serverAddress, serverPort);
						boolean isIntegrateApp = projectConfig.isIntegrateWebProject();
						boolean result = hotServerManage.createContext(appName, docBase,isIntegrateApp);
						if (result){
							ConsoleHandler.info("load application <" + appName + "> sucessfully !");				
						}else{
							ConsoleHandler.info("load application <" + appName + "> error !!");
						}
					} catch (Exception e) {
						ConsoleHandler.error(e.getLocalizedMessage());
					}
				}
			}
		};
		loadContextAction.setText("加载应用");
		loadContextAction.setToolTipText("加载应用");
		loadContextAction.setImageDescriptor(ImageUtil.getDescriptor("load"));
	}
	
	private void makeUnloadContextAction(){
		unloadContextAction = new Action() {
			public void run() {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				TreeObject treeObject = null;
				if (obj instanceof TreeObject) {
					treeObject = (TreeObject) obj;
					String appName = treeObject.getProjectName();
					ConsoleHandler.info("unloading application <" + appName + ">....");
					ProjectConfig projectConfig = MiscdpUtil.getProjectConfig(appName);
					String serverAddress = projectConfig.getServerAddress();
					String serverPort = projectConfig.getServerPort();
					try {
						HotServerManage hotServerManage = MiscdpUtil.getHotServerManage(serverAddress, serverPort);
						boolean result = hotServerManage.deleteContext(appName);
						if (result){
							ConsoleHandler.info("unload application <" + appName + "> sucessfully !");				
						}else{
							ConsoleHandler.info("unload application <" + appName + "> error !!");
						}
					} catch (Exception e) {
						ConsoleHandler.error(e.getLocalizedMessage());
					}
				}
			}
		};
		unloadContextAction.setText("卸载应用");
		unloadContextAction.setToolTipText("卸载应用");
		unloadContextAction.setImageDescriptor(ImageUtil.getDescriptor("unload"));
	}
	
	private void makeRestartContextAction(){
		restartContextAction = new Action() {
			public void run() {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				TreeObject treeObject = null;
				if (obj instanceof TreeObject) {
					treeObject = (TreeObject) obj;
					String appName = treeObject.getProjectName();
					ConsoleHandler.info("restarting application <" + appName + ">....");
					ProjectConfig projectConfig = MiscdpUtil.getProjectConfig(appName);
					String serverAddress = projectConfig.getServerAddress();
					String serverPort = projectConfig.getServerPort();
					try {
						HotServerManage hotServerManage = MiscdpUtil.getHotServerManage(serverAddress, serverPort);
						boolean result = hotServerManage.restartApplication(appName);
						if (result){
							ConsoleHandler.info("restart application <" + appName + "> sucessfully !");				
						}else{
							ConsoleHandler.info("restart application <" + appName + "> error !!");
						}
					} catch (Exception e) {
						ConsoleHandler.error(e.getLocalizedMessage());
					}
				}
			}
		};
		restartContextAction.setText("重启应用");
		restartContextAction.setToolTipText("重启应用");
		restartContextAction.setImageDescriptor(ImageUtil.getDescriptor("start"));
	}
	
	private void makeEditAppContextAction(){
		this.editContextAction = new Action() {
			public void run() {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				TreeObject treeObject = null;
				if (obj instanceof TreeObject) {
					treeObject = (TreeObject) obj;
					String appName = treeObject.getProjectName();
					IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();			
					FuncProject funcModel = new FuncProject();
					funcModel.setProjectName(appName);
					MiscdpUtil.openEditor(page,funcModel);
				}
			}
		};
		editContextAction.setText("编辑应用");
		editContextAction.setToolTipText("编辑应用");
		editContextAction.setImageDescriptor(ImageUtil.getDescriptor("editapp"));
	}
	
	
	private void makeCreateFuncAction(){
		createFuncAction = new Action() {
			public void run() {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				TreeObject parentTreeObject = (TreeObject) obj;
				String projectName = parentTreeObject.getProjectName();				
				FuncModelWizard wizard = new FuncModelWizard(projectName);
				
				wizard.init(PlatformUI.getWorkbench(),(IStructuredSelection)funcTreeViewer.getSelection());
			    WizardDialog dialog = new WizardDialog(funcTreeViewer.getControl().getShell(),wizard);
			    int returnCode = dialog.open();
				if (returnCode == Dialog.OK){
					String funcId = wizard.getNewFuncId();
					String funcName = wizard.getFuncName();
					TreeObject newNode = new TreeObject(funcId,funcName);
					newNode.setFuncType(wizard.getFuncType());
					newNode.setFuncTypeName(wizard.getFuncTypeName());
					newNode.setProjectName(projectName);
					
					parentTreeObject.addChild(newNode);
					TreeObject projectTreeObject = treeViewContentProvider.getProjectTreeObject(projectName);
					MiscdpUtil.updateTreeIndexFile(projectTreeObject);

					ShowFuncModelEditorAction showFuncModelEditorAction = new ShowFuncModelEditorAction();
					showFuncModelEditorAction.setTreeObject(newNode);
					showFuncModelEditorAction.run();
					
					Object[] elements = funcTreeViewer.getExpandedElements(); 
					TreePath[] treePaths = funcTreeViewer.getExpandedTreePaths(); 
					funcTreeViewer.refresh(); 
					funcTreeViewer.setExpandedElements(elements); 
					funcTreeViewer.setExpandedTreePaths(treePaths);
					
					ISelection newSelection = new StructuredSelection(new Object[]{newNode});
					funcTreeViewer.setSelection(newSelection);
				}
			}
		};
		createFuncAction.setText("创建功能");
		createFuncAction.setToolTipText("创建功能");
		createFuncAction.setImageDescriptor(ImageUtil.getDescriptor("add_model"));
	}
	private void makeRefreshAction(){
		refreshAction = new Action(){
			public void run() {
				TreeViewContentProvider contentProvider = (TreeViewContentProvider)funcTreeViewer.getContentProvider();
				contentProvider.initialize();
				funcTreeViewer.setInput(getViewSite());
				funcTreeViewer.refresh();
			}
		};
		refreshAction.setText("刷新");
		refreshAction.setToolTipText("刷新");
		refreshAction.setImageDescriptor(ImageUtil.getDescriptor("refresh"));		
	}

	private void makeCreateAppAction(){
		createAppAction = new Action(){
			public void run() {
				HotwebProjectWizard hotwebProjectWizard = new HotwebProjectWizard();
				Shell shell = MiscdpPlugin.getActiveWorkbenchShell();
				WizardDialog dialog = new WizardDialog(shell, hotwebProjectWizard);
				dialog.create();
				dialog.getShell().setSize(640,525);
				MiscdpUtil.centerDialog(dialog);
				dialog.setBlockOnOpen(true);
				dialog.open();
			}
		};
		createAppAction.setText("创建应用");
		createAppAction.setToolTipText("创建应用");
		createAppAction.setImageDescriptor(ImageUtil.getDescriptor("add_project"));		
	}
	
	public void refreshView(){
		refreshAction.run();
	}
	
	private void makeOpenDirAction(){
		openDirAction = new Action(){
			public void run() {
				funcTreeViewer.expandAll();
			}
		};
		openDirAction.setText("展开菜单");
		openDirAction.setToolTipText("展开菜单");
		openDirAction.setImageDescriptor(ImageUtil.getDescriptor("expand_all"));
	}
	private void makeCloseDirAction(){
		closeDirAction = new Action(){
			public void run() {
				funcTreeViewer.collapseAll();
			}
		};
		closeDirAction.setText("收合菜单");
		closeDirAction.setToolTipText("收合菜单");
		closeDirAction.setImageDescriptor(ImageUtil.getDescriptor("collapse_all"));		
	}
	private void makeDeleteNodeAction(){
		deleteNodeAction = new Action(){
			public void run() {
				ISelection selection = funcTreeViewer.getSelection();
				Object obj = ((IStructuredSelection) selection).getFirstElement();
				if (obj instanceof TreeObject) {
					TreeObject currentTreeObject = (TreeObject) obj;
					
					if (currentTreeObject.isProjectNode()){
						MessageDialog.openInformation(funcTreeViewer.getControl().getShell(),"提示信息","不能删除根节点！");
						return;
					}
					if (currentTreeObject.hasChildren()){
						MessageDialog.openInformation(funcTreeViewer.getControl().getShell(),"提示信息","该节点还有子节点，请先删除子节点！");
						return;
					}else{
						String name = currentTreeObject.getName();
						if (MessageDialog.openConfirm(funcTreeViewer.getControl().getShell(),"提示信息","您确认要删除\""+name+"\"?")){
							if (currentTreeObject.getEditor() != null){
								IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
								FuncModelTreeView.this.closeEditor(page,currentTreeObject.getEditor());
							}
							TreeViewContentProvider contentProvider = (TreeViewContentProvider)funcTreeViewer.getContentProvider();
							TreeObject parentNode = (TreeObject)contentProvider.getParent(currentTreeObject);
							parentNode.removeChild(currentTreeObject);
							
							String projectName = parentNode.getProjectName(); 
							TreeObject projectTreeObject = contentProvider.getProjectTreeObject(projectName);
							
							MiscdpUtil.updateTreeIndexFile(projectTreeObject);
							String funcId = currentTreeObject.getId();
							
							if (!StringUtil.isNullOrEmpty(currentTreeObject.getFuncType())){
								String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
								new File(fileName).delete();
							}
														
							Object[] elements = funcTreeViewer.getExpandedElements(); 
							TreePath[] treePaths = funcTreeViewer.getExpandedTreePaths(); 
							
							funcTreeViewer.refresh(); 
							funcTreeViewer.setExpandedElements(elements); 
							funcTreeViewer.setExpandedTreePaths(treePaths); 
						}
					}
				}
			}
		};
		deleteNodeAction.setText("删除节点");
		deleteNodeAction.setToolTipText("删除节点");
		deleteNodeAction.setImageDescriptor(ImageUtil.getDescriptor("delete"));
	}
	private void makeDoubleClickAction(){
		doubleClickAction = new ShowFuncModelEditorAction();	
	}
	private void makeActions() {
		makeCreateDirAction();
		makeDeleteAppAction();
		
		makeRefreshAppAction();
		makeBrowseLocalAppAction();
		makeOpenBrowserAppAction();
		makeRestartContextAction();
		makeUnloadContextAction();
		makeLoadContextAction();
		makeEditAppContextAction();
		
		makeCreateFuncAction();
		makeRefreshAction();
		makeCreateAppAction();
		makeOpenDirAction();
		makeCloseDirAction();
		makeDeleteNodeAction();
		makeDoubleClickAction();
	}
	class ShowFuncModelEditorAction extends Action{
		private TreeObject treeObject = null;
		public void run() {
			try {
				String funcId = treeObject.getId();
				IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
				String funcName = treeObject.getName();
				String funcType = treeObject.getFuncType();
				String funcTypeName = treeObject.getFuncTypeName();
				String funcSubPkg = treeObject.getFuncSubPkg();
				String projectName = treeObject.getProjectName();
				ProjectConfig projectConfig = MiscdpUtil.getProjectConfig(projectName);
				String mainPkg = projectConfig.getMainPkg();
				
				IEditorPart editor = null;
				if (StringUtil.isNullOrEmpty(funcType)){
					if (TreeObject.NODE_COMPOSITE.equals(treeObject.getNodeType())){
						FuncModule funcModel = new FuncModule();
						funcModel.setModuleId(funcId);
						funcModel.setMouleName(funcName);
						funcModel.setProjectName(projectName);
						editor = openEditor(page,funcId,funcName,funcModel);
					}else{
						FuncProject funcModel = new FuncProject();
						funcModel.setProjectName(projectName);
						editor = MiscdpUtil.openEditor(page,funcModel);
					}
				}
				else if (DeveloperConst.STANDARD_FUNCMODEL_ID.equals(funcType)){
					String funcDefine = null;
					String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
					if (new File(fileName).exists()){
						funcDefine = FileUtil.readFileByLines(fileName,null);	
					}
					StandardFuncModel funcModel = new StandardFuncModel();
					if (!StringUtil.isNullOrEmpty(funcDefine)){
						funcModel.buildFuncModel(funcDefine);
					}
					funcModel.setFuncId(funcId);
					funcModel.setFuncName(funcName);
					funcModel.setFuncType(funcType);
					funcModel.setFuncTypeName(funcTypeName);
					funcModel.setFuncSubPkg(funcSubPkg);
					funcModel.setProjectName(projectName);
					funcModel.setMainPkg(mainPkg);
					editor = openEditor(page,funcId,funcName,funcModel);
				}
				else if (DeveloperConst.MASTERSUB_FUNCMODEL_ID.equals(funcType)){
					String funcDefine = null;
					String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
					if (new File(fileName).exists()){
						funcDefine = FileUtil.readFileByLines(fileName,null);	
					}
					MasterSubFuncModel funcModel = new MasterSubFuncModel();
					if (!StringUtil.isNullOrEmpty(funcDefine)){
						funcModel.buildFuncModel(funcDefine);
					}
					funcModel.setFuncId(funcId);
					funcModel.setFuncName(funcName);
					funcModel.setFuncType(funcType);
					funcModel.setFuncTypeName(funcTypeName);
					funcModel.setFuncSubPkg(funcSubPkg);
					funcModel.setProjectName(projectName);
					funcModel.setMainPkg(mainPkg);
					editor = openEditor(page,funcId,funcName,funcModel);
				}
				else if (DeveloperConst.TREECONTENT_FUNCMODEL_ID.equals(funcType)){
					String funcDefine = null;
					String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
					if (new File(fileName).exists()){
						funcDefine = FileUtil.readFileByLines(fileName,null);	
					}
					TreeContentFuncModel funcModel =  new TreeContentFuncModel();
					if (!StringUtil.isNullOrEmpty(funcDefine)){
						funcModel.buildFuncModel(funcDefine);
					}
					funcModel.setFuncId(funcId);
					funcModel.setFuncName(funcName);
					funcModel.setFuncType(funcType);
					funcModel.setFuncTypeName(funcTypeName);
					funcModel.setFuncSubPkg(funcSubPkg);
					funcModel.setProjectName(projectName);
					funcModel.setMainPkg(mainPkg);
					editor = openEditor(page,funcId,funcName,funcModel);
				}
				else if (DeveloperConst.QUERY_FUNCMODEL_ID.equals(funcType)){
					String funcDefine = null;
					String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
					if (new File(fileName).exists()){
						funcDefine = FileUtil.readFileByLines(fileName,null);	
					}
					QueryFuncModel funcModel = new QueryFuncModel();
					if (!StringUtil.isNullOrEmpty(funcDefine)){
						funcModel.buildFuncModel(funcDefine);
					}
					funcModel.setFuncId(funcId);
					funcModel.setFuncName(funcName);
					funcModel.setFuncType(funcType);
					funcModel.setFuncTypeName(funcTypeName);
					funcModel.setFuncSubPkg(funcSubPkg);
					funcModel.setProjectName(projectName);
					funcModel.setMainPkg(mainPkg);
					editor = openEditor(page,funcId,funcName,funcModel);
				}
				else if (DeveloperConst.PICKFILL_FUNCMODEL_ID.equals(funcType)){
					String funcDefine = null;
					String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
					if (new File(fileName).exists()){
						funcDefine = FileUtil.readFileByLines(fileName,null);	
					}
					PickFillFuncModel funcModel = new PickFillFuncModel();
					if (!StringUtil.isNullOrEmpty(funcDefine)){
						funcModel.buildFuncModel(funcDefine);
					}
					funcModel.setFuncId(funcId);
					funcModel.setFuncName(funcName);
					funcModel.setFuncType(funcType);
					funcModel.setFuncTypeName(funcTypeName);
					funcModel.setFuncSubPkg(funcSubPkg);
					funcModel.setProjectName(projectName);
					funcModel.setMainPkg(mainPkg);
					editor = openEditor(page,funcId,funcName,funcModel);
				}
				else if (DeveloperConst.TREEFILL_FUNCMODEL_ID.equals(funcType)){
					String funcDefine = null;
					String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
					if (new File(fileName).exists()){
						funcDefine = FileUtil.readFileByLines(fileName,null);	
					}
					TreeFillFuncModel funcModel = new TreeFillFuncModel();
					if (!StringUtil.isNullOrEmpty(funcDefine)){
						funcModel.buildFuncModel(funcDefine);
					}
					funcModel.setFuncId(funcId);
					funcModel.setFuncName(funcName);
					funcModel.setFuncType(funcType);
					funcModel.setFuncTypeName(funcTypeName);
					funcModel.setFuncSubPkg(funcSubPkg);
					funcModel.setProjectName(projectName);
					funcModel.setMainPkg(mainPkg);
					editor = openEditor(page,funcId,funcName,funcModel);
				}
				else if (DeveloperConst.TREEMANAGE_FUNCMODEL_ID.equals(funcType)){
					String funcDefine = null;
					String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
					if (new File(fileName).exists()){
						funcDefine = FileUtil.readFileByLines(fileName,null);	
					}
					TreeManageFuncModel funcModel = new TreeManageFuncModel();
					if (!StringUtil.isNullOrEmpty(funcDefine)){
						funcModel.buildFuncModel(funcDefine);
					}
					funcModel.setFuncId(funcId);
					funcModel.setFuncName(funcName);
					funcModel.setFuncType(funcType);
					funcModel.setFuncTypeName(funcTypeName);
					funcModel.setFuncSubPkg(funcSubPkg);
					funcModel.setProjectName(projectName);
					funcModel.setMainPkg(mainPkg);
					editor = openEditor(page,funcId,funcName,funcModel);
				}					
				else if (DeveloperConst.CUSTOM_FUNCMODEL_ID.equals(funcType)){
					CustomFuncModel funcModel = new CustomFuncModel();
					funcModel.setFuncId(funcId);
					funcModel.setFuncName(funcName);
					funcModel.setFuncType(funcType);
					funcModel.setFuncTypeName(funcTypeName);
					funcModel.setFuncSubPkg(funcSubPkg);
					funcModel.setProjectName(projectName);
					funcModel.setMainPkg(mainPkg);
					editor = openEditor(page,funcId,funcName,funcModel);
				}
				else if (DeveloperConst.SIMPLE_FUNCMODEL_ID.equals(funcType)){
					String funcDefine = null;
					String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
					if (new File(fileName).exists()){
						funcDefine = FileUtil.readFileByLines(fileName,null);	
					}
					SimplestFuncModel funcModel = new SimplestFuncModel();
					if (!StringUtil.isNullOrEmpty(funcDefine)){
						funcModel.buildFuncModel(funcDefine); 
					}
					funcModel.setFuncId(funcId);
					funcModel.setFuncName(funcName);
					funcModel.setFuncType(funcType);
					funcModel.setFuncTypeName(funcTypeName);
					funcModel.setFuncSubPkg(funcSubPkg);
					funcModel.setProjectName(projectName);
					funcModel.setMainPkg(mainPkg);
					editor = openEditor(page,funcId,funcName,funcModel);
				}
				else if (DeveloperConst.PORTLET_FUNCMODEL_ID.equals(funcType)){
					String funcDefine = null;
					String fileName = MiscdpUtil.getFuncFileName(projectName,funcId);
					if (new File(fileName).exists()){
						funcDefine = FileUtil.readFileByLines(fileName,null);	
					}
					PortletFuncModel funcModel = new PortletFuncModel();
					if (!StringUtil.isNullOrEmpty(funcDefine)){
						funcModel.buildFuncModel(funcDefine); 
					}
					funcModel.setFuncId(funcId);
					funcModel.setFuncName(funcName);
					funcModel.setFuncType(funcType);
					funcModel.setFuncTypeName(funcTypeName);
					funcModel.setFuncSubPkg(funcSubPkg);
					funcModel.setProjectName(projectName);
					funcModel.setMainPkg(mainPkg);
					editor = openEditor(page,funcId,funcName,funcModel);
				}				
				treeObject.setEditor(editor);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		public void setTreeObject(TreeObject treeObject) {
			this.treeObject = treeObject;
		}
	}
	
	private void closeEditor(IWorkbenchPage page,IEditorPart editor){
		page.closeEditor(editor,true);
	}
	
	private IEditorPart openEditor(IWorkbenchPage page,String funcId, String funcName,FuncModule funcModule){
		IEditorPart editor = null;
		boolean flags = false;
		IEditorReference[] editors = page.getEditorReferences();
		for (int i = 0; i < editors.length; i++) {
			String oldTitleToolTip = editors[i].getTitleToolTip();
			if (FuncModule.getTipText(funcId, funcName).equals(oldTitleToolTip)) {
				flags = true;
				editor = editors[i].getEditor(true);
				break;
			}
		}
		if (flags) {
			page.bringToTop(editor);
		} else {
			try {
				editor = page.openEditor(funcModule,funcModule.getEditorId());
			} catch (PartInitException e) {
				e.printStackTrace();
			}
			((FuncModuleEditor)editor).setFuncModelTree(this);
		}
		return editor;
	}

	private IEditorPart openEditor(IWorkbenchPage page,String funcId, String funcName,BaseFuncModel baseFuncModel){
		IEditorPart editor = null;
		boolean flags = false;
		IEditorReference[] editors = page.getEditorReferences();
		for (int i = 0; i < editors.length; i++) {
			String oldTitleToolTip = editors[i].getTitleToolTip();
			if (BaseFuncModel.getTipText(funcId, funcName).equals(oldTitleToolTip)) {
				flags = true;
				editor = editors[i].getEditor(true);
				break;
			}
		}
		if (flags) {
			page.bringToTop(editor);
		} else {
			try {
				editor = page.openEditor(baseFuncModel,baseFuncModel.getEditorId());
			} catch (PartInitException e) {
				e.printStackTrace();
			}
			if (editor instanceof StandardModelEditor){
				((StandardModelEditor)editor).setFuncModelTree(this);
			}
			else if (editor instanceof MasterSubModelEditor){
				((MasterSubModelEditor)editor).setFuncModelTree(this);
			}
			else if (editor instanceof TreeContentModelEditor){
				((TreeContentModelEditor)editor).setFuncModelTree(this);
			}
			else if (editor instanceof QueryModelEditor) {
				((QueryModelEditor)editor).setFuncModelTree(this);
			}
			else if (editor instanceof PickFillModelEditor) {
				((PickFillModelEditor)editor).setFuncModelTree(this);
			}
			else if (editor instanceof TreeFillModelEditor) {
				((TreeFillModelEditor)editor).setFuncModelTree(this);
			}
			else if (editor instanceof TreeManageModelEditor) {
				((TreeManageModelEditor)editor).setFuncModelTree(this);
			}
			else if (editor instanceof SimplestModelEditor){
				((SimplestModelEditor)editor).setFuncModelTree(this);
			}
			else if (editor instanceof PortletModelEditor){
				((PortletModelEditor)editor).setFuncModelTree(this);
			}			
		}
		return editor;
	}
	private void hookDoubleClickAction() {
		funcTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doDoubleClickAction();
			}
		});
	}
	private void doDoubleClickAction(){
		ISelection selection = funcTreeViewer.getSelection();
		Object obj = ((IStructuredSelection) selection).getFirstElement();
		if (obj instanceof TreeObject) {
			TreeObject curNode = (TreeObject) obj;
			((ShowFuncModelEditorAction)doubleClickAction).setTreeObject(curNode);
			doubleClickAction.run();
		}
	}
	public void setFocus() {
		funcTreeViewer.getControl().setFocus();
	}
}
